package net.jiastudy.core.base;

import java.sql.DatabaseMetaData;
import java.util.List;
import java.util.Map;

import org.flywaydb.core.api.migration.spring.BaseSpringJdbcMigration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

public abstract class BaseMigration extends BaseSpringJdbcMigration {

	protected JdbcTemplate jdbcTemplate;

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Override
	public void migrate(JdbcTemplate jdbcTemplate) throws Exception {
		this.jdbcTemplate = jdbcTemplate;
		this.migrate();
	}
	
	public abstract void migrate() throws Exception;

	protected boolean isTableExist(String tableName) {
		String sql = "SHOW TABLES LIKE '" + tableName + "'";
		List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
		if (null != rows && rows.size() > 0) {
			return true;
		}
		return false;
	}

	protected boolean isFieldExist(String tableName, String columnName) {
		String sql = "SHOW COLUMNS from `" + tableName + "` ";
		List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
		for (Map<String, Object> map : rows) {
			String field = (String) map.get("field");
			if (field.equalsIgnoreCase(columnName)) {
				return true;
			}
		}
		return false;
	}

	protected boolean isIndexExist(String tableName, String keyName) {
		String sql = "show index from user where key_name = '" + keyName + "';";
		List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
		if (null != rows && rows.size() > 0) {
			return true;
		}
		return false;
	}
	
	protected boolean isH2() {
		try {
			DatabaseMetaData md = this.jdbcTemplate.getDataSource().getConnection().getMetaData();
			String dbName = md.getDatabaseProductName();
			return "H2".equalsIgnoreCase(dbName);
		} catch (Exception e) {
			logger.error("出错了：", e);
		}
		return false;
	}
}
